﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Slam.SharePoint;

namespace SlamCms.SharePoint.Core
{
	public class SharePointList : SharePointAction<SharePointList>
	{
		private SharePointSite _site;

		public SharePointList() :
			base()
		{
			_site = new SharePointSite(SharePointItem);
		}

		public SharePointList(SharePointItem baseItem)
		{
			SharePointItem = baseItem;
			_site = new SharePointSite(SharePointItem);
		}

		
		public void Item(string slamId, Action<SPListItem> action)
		{
			SharePointItem.SlamId = slamId;
			if (!String.IsNullOrEmpty(SharePointItem.ListName))
			{
				_site.List(SharePointItem.ListName, l =>
				{
					action.Invoke(l.GetItemBySlamId(SharePointItem.SlamId));
				});
			} 
			else if (SharePointItem.ListId != Guid.Empty)
			{
				_site.List(SharePointItem.ListId, l =>
				{
					action.Invoke(l.GetItemBySlamId(SharePointItem.SlamId));
				});
			}
		}

		public void Item(int listRelativeId, Action<SPListItem> action)
		{
			SharePointItem.ListRelativeId = listRelativeId;
			if (!String.IsNullOrEmpty(SharePointItem.ListName))
			{
				_site.List(SharePointItem.ListName, l =>
				{
					action.Invoke(l.GetItemById(SharePointItem.ListRelativeId));
				});
			}
			else if (SharePointItem.ListId != Guid.Empty)
			{
				_site.List(SharePointItem.ListId, l =>
				{
					action.Invoke(l.GetItemById(SharePointItem.ListRelativeId));
				});
			}
		}

		public void Item(Guid uniqueId, Action<SPListItem> action)
		{
			SharePointItem.ListItemId = uniqueId;
			if (!String.IsNullOrEmpty(SharePointItem.ListName))
			{
				_site.List(SharePointItem.ListName, l =>
				{
					action.Invoke(l.GetItemByUniqueId(SharePointItem.ListItemId));
				});
			}
			else if (SharePointItem.ListId != Guid.Empty)
			{
				_site.List(SharePointItem.ListId, l =>
				{
					action.Invoke(l.GetItemByUniqueId(SharePointItem.ListItemId));
				});
			}
		}

		public void NewItem(Action<SPListItem> action)
		{	
			if (!String.IsNullOrEmpty(SharePointItem.ListName))
			{
				_site.List(SharePointItem.ListName, l =>
				{
					action.Invoke(l.AddItem());
				});
			}
			else if (SharePointItem.ListId != Guid.Empty)
			{
				_site.List(SharePointItem.ListId, l =>
				{
					action.Invoke(l.AddItem());
				});
			}
		}

		public void NewItem(Action<SPListItem, SPList> action)
		{
			if (!String.IsNullOrEmpty(SharePointItem.ListName))
			{
				_site.List(SharePointItem.ListName, l =>
				{
					action.Invoke(l.AddItem(), l);
				});
			}
			else if (SharePointItem.ListId != Guid.Empty)
			{
				_site.List(SharePointItem.ListId, l =>
				{
					action.Invoke(l.AddItem(), l);
				});
			}
		}
	}
}
